package com.cameron.serviceedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cameron.entity.EduCourseCollect;
import com.cameron.serviceedu.entity.viewobject.CollectVo;
import com.cameron.serviceedu.mapper.EduCourseCollectMapper;
import com.cameron.serviceedu.service.EduCourseCollectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

import static com.cameron.constant.CollectCourseConstant.COLLECT_KEY_PREFIX;

/**
 * @author Mind
 * @description 针对表【edu_course_collect(课程收藏)】的数据库操作Service实现
 * @createDate 2023-01-12 11:23:42
 */
@Service
public class EduCourseCollectServiceImpl extends ServiceImpl<EduCourseCollectMapper, EduCourseCollect>
        implements EduCourseCollectService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean isCollected(CollectVo collectVo) {
        String courseId = collectVo.getCourseId();
        String userId = collectVo.getUserId();
        if (StringUtils.isAnyBlank(courseId, userId)) return false;
        String collectKey = COLLECT_KEY_PREFIX + courseId;
        Boolean isMember = redisTemplate.opsForSet().isMember(collectKey, userId);
        //判断该用户是否已收藏课程。
        isMember = Optional.ofNullable(isMember).orElse(false);
        //若用户没有收藏，存入redis的set集合中
        if (!isMember){
            redisTemplate.opsForSet().add(collectKey,userId);
        }
        return isMember;
    }

    @Override
    public void removeByCollectVo(CollectVo collectVo) {
        LambdaQueryWrapper<EduCourseCollect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduCourseCollect::getCourseId, collectVo.getCourseId())
                .eq(EduCourseCollect::getMemberId, collectVo.getUserId());
        this.remove(wrapper);
    }
}




